package com.azusa.xbiao.controller;

import com.azusa.xbiao.entity.Result;
import com.azusa.xbiao.entity.StatusCode;
import com.azusa.xbiao.entity.User;
import com.azusa.xbiao.service.ResourceService;
import com.azusa.xbiao.service.UserService;
import com.azusa.xbiao.utils.EmailUtil;
import com.azusa.xbiao.utils.IdWorker;
import com.azusa.xbiao.utils.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/")
public class CommonController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpSession session;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private ResourceService resourceService;

    @RequestMapping("header")
    public ModelAndView toHeader(){
        return new ModelAndView("/header");
    }
    @RequestMapping("foot")
    public ModelAndView toFoot(){
        return new ModelAndView("/foot");
    }
    @RequestMapping("home")
    public ModelAndView toHome(){
        return new ModelAndView("/home");
    }
    @RequestMapping("toLogin")
    public ModelAndView toLogin(){
        return new ModelAndView("/login");
    }

    @RequestMapping("register")
    public ModelAndView toRegister(){
        return new ModelAndView("/register");
    }
    @RequestMapping("changePwd")
    public ModelAndView toChangePwd(){
        return new ModelAndView("/changePwd");
    }

    /**
     * 登录用户
     * @param username
     * @param password
     * @param code
     * @return
     */
    @RequestMapping("login")
    public Result doLogin(String username,String password,String code){
        //获取正确的验证码信息
        String checkCode = (String) session.getAttribute("checkCode");
        if (checkCode!=null && checkCode.equals(code)){
            User loginUser = userService.findByUsernameAndPassword(username, password);
            if (loginUser != null){
                //将登录用户存储到session和redis中
                loginUser.setPassword(null);
                session.setAttribute("userId",loginUser.getId());
                redisTemplate.opsForValue().set("loginUser:" + loginUser.getId(),loginUser,2, TimeUnit.HOURS);
                return new Result(StatusCode.SUCCESS,loginUser);
            }
            return new Result(StatusCode.USER_PASSWORD_ERROR);
        }
        return new Result(StatusCode.NO_CODE);
    }

    /**
     * 注销用户
     * @param session
     * @return
     */
    @RequestMapping("logout")
    public ModelAndView toLogout(HttpSession session){
        //清除session中的user信息
        session.removeAttribute("userId");
        redisTemplate.delete("loginUser:"+ LoginUserUtil.getId());
        //跳回首页
        return new ModelAndView("redirect:toLogin");
    }

    /**
     * 查看邮箱是否已被注册
     * @param email
     * @return
     */
    @RequestMapping("checkEmail/{email}")
    public Result checkEmail(@PathVariable("email") String email){
        User user = userService.findByEmail(email);
        if (user != null){
            //用户已被注册
            return new Result(StatusCode.ERROR,"该邮箱已被注册，请重新输入");
        }
        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 查看用户名是否已被注册
     * @param username
     * @return
     */
    @RequestMapping("checkUserName/{username}")
    public Result checkUserName(@PathVariable("username") String username){
        User user = userService.findByUsername(username);
        if (user != null){
            //用户已被注册
            return new Result(StatusCode.ERROR,"该用户名已被注册，请重新输入");
        }
        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping("doRegister")
    public Result register(@RequestBody User user){
        if (StringUtils.isEmpty(user.getEmail())){
            return new Result(StatusCode.ERROR,"邮箱为空，请重新输入");
        }
        if (StringUtils.isEmpty(user.getUsername())){
            return new Result(StatusCode.ERROR,"用户名为空，请重新输入");
        }
        if (StringUtils.isEmpty(user.getPassword())){
            return new Result(StatusCode.ERROR,"密码为空，请重新输入");
        }
        //...一系列检验
        user.setRealName(user.getUsername());
        //头像
        user.setPic("http://192.168.31.240:8080/upload/user/default.jpg");
        //默认为男
        user.setGender(0);
        user.setAge(21);
        user.setcId(new Random().nextInt(65534));
        user.setCountry("Chinese");
        user.setAge(18);
        user.setIntro("Java开发工程师");
        userService.save(user);
        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 发送验证码到指定邮箱
     * @param email
     * @return
     */
    @PutMapping("sendCode/{email}")
    public Result sendCode(@PathVariable("email") String email){
        //生成6位随机验证码
        String code = emailUtil.getCode(6);
        //将验证码放入缓存
        redisTemplate.opsForValue().set("code:" + email,code,10,TimeUnit.MINUTES);
        emailUtil.sendMail(email,"主题：小标验证码",code);
        return new Result(StatusCode.SUCCESS,"发送成功");
    }

    /**
     * 修改用户密码
     * @param code
     * @param params
     * @return
     */
    @RequestMapping("updatePassword/{code}")
    public Result updatePassword(@PathVariable("code")String code,@RequestBody Map<String,String> params){
        String email = params.get("email");
        String checkCode = (String) redisTemplate.opsForValue().get("code:" + email);
        if (checkCode !=null && checkCode.equals(code)){
            User user = userService.findByUsernameAndEmail(params.get("username"),params.get("email"));
            if (user == null){
                redisTemplate.delete("code:" + email);      //清空验证码
                return new Result(StatusCode.ERROR,"用户名和邮箱不匹配，请重新输入");
            }
            user.setPassword(params.get("password"));
            userService.save(user);
            return new Result(StatusCode.SUCCESS);
        }else {
            return new Result(StatusCode.ERROR,"验证码信息错误，请重新发送");
        }
    }

    @RequestMapping("initNav")
    public Result initNav(){
        return new Result(StatusCode.SUCCESS,resourceService.findAll());
    }
}
